<template>
  <div class="search">
    <h1>账单管理</h1>
    <hr style="border: 1px solid rgb(240, 240, 240)" />
    <span>缴纳状态</span>
    <el-select
      v-model="pay_status"
      style="width: 200px"
      placeholder="请选择缴纳状态"
    >
      <el-option
        v-for="item in options1"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <span>收费项目</span>
    <el-select v-model="pay_item" style="width: 200px" placeholder="请选择">
      <el-option
        v-for="item in options2"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <br />
    <span>精确查询</span>
    <el-select
      v-model="select"
      style="width: 150px; margin-right: 1rem"
      placeholder="请选择"
    >
      <el-option
        v-for="item in options3"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-input
      v-model="value"
      style="width: 200px; margin-right: 25%"
      placeholder="请输入"
    ></el-input>
    <el-button type="primary" @click="fetchBillData">查询</el-button>
    <el-button type="default" @click="handleReset">重置</el-button>
  </div>
  <div class="page">
    <div class="page-header">
      <div class="page-header-left">
        <span>账单列表</span>
      </div>
      <div class="page-header-right">
        <el-button
          type="primary"
          style="margin-top: 1rem"
          @click="to('payment/newBill')"
        >
          +&nbsp;新建账单
        </el-button>
        <el-button
          type="default"
          style="margin-top: 1rem; margin-right: 3rem"
          @click="deleteDialog = true"
          >批量删除</el-button
        >
        <el-dialog v-model="deleteDialog" title="警告" width="500" align-center>
          <span>是否删除选中的信息，该操作不可撤回！</span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteDialog = false">取消</el-button>
              <el-button type="primary" @click="deleteByIds"> 确认 </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column property="roomNumber" label="房间号" />
      <el-table-column property="householdName" label="住户姓名" />
      <el-table-column property="item" label="收费项目" />
      <el-table-column property="unitPrice" label="单价" />
      <el-table-column property="totalAmount" label="费用合计" />
      <el-table-column label="缴费状态">
        <template #default="{ row }">
          {{ getPaymentStatus(row.status) }}
        </template>
      </el-table-column>
      <el-table-column property="lateFeeRate" label="滞纳金率" />
      <!-- <el-table-column label="开始日期">
        <template #default="{ row }">
          {{ formatDate(row.startDate) }}
        </template>
      </el-table-column>
      <el-table-column label="结束日期">
        <template #default="{ row }">
          {{ formatDate(row.endDate) }}
        </template>
      </el-table-column> -->
      <el-table-column property="remark" label="备注" />
      <el-table-column label="操作" width="140">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row.id)">编辑</el-button>
          <el-button type="text" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        style="margin-bottom: 2rem"
        background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElTable, ElMessageBox, ElMessage } from "element-plus";
import axios from "axios";
import to from "@/utils/to.js";
import router from "@/router";

const loading = ref(false);
const deleteDialog = ref(false);

const pay_status = ref("");
const pay_item = ref("");
const select = ref("");
const value = ref("");

const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
const selectRows = ref([]);

const options1 = [
  {
    value: "",
    label: "全部",
  },
  {
    value: 0,
    label: "待缴费",
  },
  {
    value: 1,
    label: "已缴费",
  },
];

const options2 = ref([]);

const options3 = [
  {
    value: "账单名称",
    label: "账单名称",
  },
  {
    value: "账单编号",
    label: "账单编号",
  },
  {
    value: "房间号码",
    label: "房间号码",
  },
  {
    value: "住户姓名",
    label: "住户姓名",
  },
];

const formatDate = (timestamp) => {
  return new Date(timestamp).toLocaleDateString();
};

const getPaymentStatus = (status) => {
  return status === 1 ? "已缴费" : "待缴费";
};

const fetchBillData = async () => {
  try {
    const params = {
      page: pageNum.value,
      pageSize: pageSize.value,
      billNumber: select.value === "账单编号" ? value.value : null,
      billName: select.value === "账单名称" ? value.value : null,
      roomNumber: select.value === "房间号码" ? value.value : null,
      householdName: select.value === "住户姓名" ? value.value : null,
      item: pay_item.value,
      status: pay_status.value === "" ? null : pay_status.value === 1 ? 0 : 1,
    };

    const response = await axios.get("http://localhost:8080/pay/bill/page", {
      headers: {
        Authorization: localStorage.getItem("token"),
      },
      params: params,
    });
    if (response.data.code === 1) {
      tableData.value = response.data.data.records;
      total.value = response.data.data.total;
    } else {
      console.error("Failed to fetch bill data:", response.data.msg);
    }
  } catch (error) {
    console.error("Error fetching bill data:", error);
  }
};

onMounted(() => {
  fetchBillData();
});

const handleSelectionChange = (selectedRows) => {
  selectRows.value = selectedRows;
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchBillData();
};

const handlePageChange = (newPage) => {
  pageNum.value = newPage;
  fetchBillData();
};

const handleReset = () => {
  pay_status.value = "";
  pay_item.value = "";
  select.value = "";
  value.value = "";
  fetchBillData();
};

const handleEdit = (id) => {
  router.push({ path: "/backend/payment/newBill", query: { id: id } });
};

const handleDelete = async (id) => {
  try {
    const confirmDelete = await ElMessageBox.confirm(
      "确定要删除该账单吗？",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    if (confirmDelete) {
      const response = await axios.delete(
        `http://localhost:8080/pay/bill/${id}`
      );
      if (response.data.code === 1) {
        fetchBillData();
        ElMessageBox.alert("删除成功", "成功", { type: "success" });
      } else {
        console.error("删除失败:", response.data.msg);
        ElMessageBox.alert("删除失败", "错误", { type: "error" });
      }
    }
  } catch (error) {
    console.error("删除时出错:", error);
    ElMessageBox.alert("删除时出错", "错误", { type: "error" });
  }
};

const deleteByIds = () => {
  if (selectRows.value.length === 0) {
    ElMessage({
      message: "请选择要删除的信息",
      type: "warning",
    });
    deleteDialog.value = false;
    return;
  }

  const config = {
    url: "http://localhost:8080/pay/bill/deleteByIds",
    method: "DELETE",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
    data: selectRows.value.map(item => item.id),
  };

  const response = axios(config);
  response
    .then((data) => {
      if (data.data.code === 1) {
        ElMessage({
          message: data.data.msg,
          type: "success",
        });
        setTimeout(() => {
          fetchBillData();
        }, 2000);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  deleteDialog.value = false;
};
</script>

<style scoped>
.search {
  background-color: white;
  padding-bottom: 2rem;
  height: auto;
  margin-top: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin-top: 2rem;
  margin-left: 3rem;
  margin-right: 1rem;
  height: 24px;
}

.page {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  margin-top: 2rem;
  justify-content: center;
}
</style>
